package com.baidu.iit.pvm.runtime;

import com.baidu.iit.pvm.PvmEventConstacts;
import com.baidu.iit.pvm.process.ActivityImpl;
import com.baidu.iit.pvm.process.ProcessDefinitionImpl;
import com.baidu.iit.pvm.process.ScopeImpl;

import java.util.List;

/**
 * 流程开始初始化操作
 *
 * @ThreadSafe
 * Created by 卫立 on 2014/4/7.
 */
public class AtomicOperationProcessStartInitial extends AbstractEventAtomicOperation {

    @Override
    protected ScopeImpl getScope(InterpretableExecution execution) {
        return (ScopeImpl) execution.getActivity();
    }

    @Override
    protected String getEventName() {
        return PvmEventConstacts.EVENTNAME_START;
    }

    @Override
    protected void eventNotificationsCompleted(InterpretableExecution execution) {

        ActivityImpl activity = (ActivityImpl) execution.getActivity();
        ProcessDefinitionImpl processDefinition = execution.getProcessDefinition();

        StartingExecution startingExecution = execution.getStartingExecution();

        //当已经初始化过了就不再进行启动操作
        if (activity==startingExecution.getInitial()) {
            execution.disposeStartingExecution();
            execution.performOperation(ACTIVITY_EXECUTE);
        } else {
            List<ActivityImpl> initialActivityStack = processDefinition.getInitialActivityStack(startingExecution.getInitial());
            int index = initialActivityStack.indexOf(activity);
            activity = initialActivityStack.get(index+1);

            InterpretableExecution executionToUse = null;
            if (activity.isScope()) {
                executionToUse = (InterpretableExecution) execution.getExecutions().get(0);
            } else {
                executionToUse = execution;
            }
            executionToUse.setActivity(activity);
            executionToUse.performOperation(PROCESS_START_INITIAL);
        }
    }
}
